package com.simple.piger.controller;

import com.simple.piger.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;

/**
 * @date 2018/1/16 19:17
 * 钉钉异常信息跳转ActionCard信息
 */
@Controller
public class DingTalkExceptionController {
    /**
     * 专门处理钉钉发送异常的信息
     * @param request
     * @param map
     * @return
     */
    @RequestMapping("/dingding/exception/info")
    public String serverExceptionInfo(HttpServletRequest request, ModelMap map) {
        String info = request.getParameter("exception");
        if (StringUtils.isBlank(info)) {
            map.addAttribute("info", "请求参数的值是空，可能传给钉钉的回调URL错误");
            return "exception-info";
        }
        try {
            info = URLDecoder.decode(info, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (StringUtils.isBlank(info)) {
            map.addAttribute("info", "转义URL中的值失败");
            return "exception-info";
        }
        //这里是因为浏览器将URL中的+号变成了空格" ",这里需要转换
        info = info.replace(" ", "+");
        //解压
        try {
            info = StringUtil.gunzip(info);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (StringUtils.isBlank(info)) {
            map.addAttribute("info", "解压缩URL中的值失败");
            return "exception-info";
        }
        List<String> list = Arrays.asList(info.split("\\)"));
        StringBuilder sb = new StringBuilder(info.length() + 1000);
        int num = 0;
        for (String str : list) {
            num++;
            if (str.contains("mfcar") || num <= 3) {
                sb.append("<strong>");
            }
            sb.append(str);
            sb.append(")");
            if (str.contains("mfcar") || num <= 3) {
                sb.append("</strong>");
            }
            sb.append("\n");
        }
        map.addAttribute("info", sb.toString());
        return "exception-info";
    }
}
